package com.hzeport.bgs22emduty.config;

import com.hzeport.bgs22emduty.config.exception.HdcException;
import com.hzeport.bgs22emduty.entity.ErrLog;
import com.hzeport.bgs22emduty.outbound.ErrLogRepository;
import com.hzeport.bgs22emduty.common.base.BaseResult;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;

/**
 * @author hzeport
 */
@ControllerAdvice()
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @Resource
    private ErrLogRepository errLogRepository;
    @Resource
    private ServletContext   servletContext;
    @Value("${spring.application.name}")
    private String   appName;



    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public BaseResult<String> handler(MethodArgumentNotValidException e) {
        log.error("实体校验异常：----------------{}", e.getMessage(), e);
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().orElse(new ObjectError("", ""));
        return BaseResult.failed(objectError.getDefaultMessage());
    }

    @ExceptionHandler(HdcException.class)
    public BaseResult<String> handleException(HdcException ex) {
        InetAddress localHost = this.getLocalHost();
        //插入新的报错信息
        ErrLog errLog = new ErrLog();
        if (localHost == null) {
            errLog.setServerName(localHost.getHostName());
            errLog.setServerIP(localHost.getHostAddress());
        }
//        errLog.setClientIP();
//        errLog.setClientName();
        errLog.setName(appName);
        errLog.setErrMsg(ex.getMessage());
        errLog.setErrTime(LocalDateTime.now());
        errLogRepository.save(errLog);
        log.error("记录到异常", ex);
        return BaseResult.failed("操作失败，原因为" + ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public BaseResult<String> handleException(Exception ex, HttpServletRequest request) {
        log.error("记录到异常", ex);
        return BaseResult.failed("操作失败，原因为" + ex.getMessage());
    }

    public InetAddress getLocalHost() {
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            return localHost;
        } catch (UnknownHostException e) {
            return null;
        }
    }
}
